﻿
using Dapper;
using System;
using BCEntity.MySql.BusinessFlowInstance;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.MySql.BusinessFlowInstance
{
    /// <summary>
    /// OA系统业务流实例
    /// </summary>
    public class BusinessFlowInstanceData : IBusinessFlowInstanceData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM OA_BusinessFlowInstance";
        private const string QUERY = @"SELECT BusinessFlowInstanceId,BusinessFlowInstanceName,BusinessFlowModelId,BusinessFlowModelName,BusinessFlowModelCode,BusinessFlowCategoryId,
                                            BusinessFlowCategoryName,CompanyId,CompanyName,TotalStep,CurrentlyStep,BusinessTaskLevel,
                                            CreateTime,IsGroupBusiness,IsClosed,ClosedRemark,CloseAdminId,CloseAdminName,CloseTime 
                                        FROM OA_BusinessFlowInstance";
        public BusinessFlowInstanceData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public async Task<bool> Exists(long businessFlowInstanceId)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowInstanceId=?BusinessFlowInstanceId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowInstanceId", businessFlowInstanceId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> InUsed(long businessFlowModelId)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowModelId=?BusinessFlowModelId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelId", businessFlowModelId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        public async Task<BusinessFlowInstanceEntity> Add(BusinessFlowInstanceEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("OA_BusinessFlowInstance", new string[] { "BusinessFlowInstanceName", "BusinessFlowModelId", "BusinessFlowModelName", "CompanyId",
                "CompanyName", "TotalStep", "CurrentlyStep", "IsGroupBusiness","BusinessFlowModelCode","BusinessFlowCategoryId","BusinessFlowCategoryName","BusinessTaskLevel" });
            sql = string.Format("{0} {1} WHERE BusinessFlowInstanceId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowInstanceName", entity.BusinessFlowInstanceName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?BusinessFlowModelId", entity.BusinessFlowModelId, DbType.Int64, size: 20);
            parameters.Add("?BusinessFlowModelName", entity.BusinessFlowModelName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?BusinessFlowModelCode", entity.BusinessFlowModelCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?BusinessFlowCategoryId", entity.BusinessFlowCategoryId, DbType.Int64, size: 20);
            parameters.Add("?BusinessFlowCategoryName", entity.BusinessFlowCategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?BusinessTaskLevel", entity.BusinessTaskLevel.ToString(), DbType.AnsiString);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
            parameters.Add("?CompanyName", entity.CompanyName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?TotalStep", entity.TotalStep, DbType.Int32, size: 11);
            parameters.Add("?CurrentlyStep", entity.CurrentlyStep, DbType.Int32, size: 11);
            parameters.Add("?IsGroupBusiness", entity.IsGroupBusiness, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<BusinessFlowInstanceEntity>(sql, parameters, databaseContext.Transaction);

        }

        public async Task<BusinessFlowInstanceEntity> Update(BusinessFlowInstanceEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("OA_BusinessFlowInstance", new string[] { "BusinessFlowInstanceName", "BusinessFlowModelId", "BusinessFlowModelName", "CompanyId",
                "CompanyName", "TotalStep", "CurrentlyStep", "IsGroupBusiness","BusinessFlowModelCode","BusinessFlowCategoryId","BusinessFlowCategoryName","BusinessTaskLevel"  },
                new string[] { "BusinessFlowInstanceId" });
            sql = string.Format("{0} {1} WHERE BusinessFlowInstanceId=?BusinessFlowInstanceId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowInstanceId", entity.BusinessFlowInstanceId, DbType.Int64, size: 20);
            parameters.Add("?BusinessFlowInstanceName", entity.BusinessFlowInstanceName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?BusinessFlowModelId", entity.BusinessFlowModelId, DbType.Int64, size: 20);
            parameters.Add("?BusinessFlowModelName", entity.BusinessFlowModelName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?BusinessFlowModelCode", entity.BusinessFlowModelCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?BusinessFlowCategoryId", entity.BusinessFlowCategoryId, DbType.Int64, size: 20);
            parameters.Add("?BusinessFlowCategoryName", entity.BusinessFlowCategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?BusinessTaskLevel", entity.BusinessTaskLevel.ToString(), DbType.AnsiString);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
            parameters.Add("?CompanyName", entity.CompanyName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?TotalStep", entity.TotalStep, DbType.Int32, size: 11);
            parameters.Add("?CurrentlyStep", entity.CurrentlyStep, DbType.Int32, size: 11);
            parameters.Add("?IsGroupBusiness", entity.IsGroupBusiness, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<BusinessFlowInstanceEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<bool> Delete(long businessFlowInstanceId)
        {
            string sql = @"DELETE FROM OA_BusinessFlowInstance WHERE BusinessFlowInstanceId=?BusinessFlowInstanceId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowInstanceId", businessFlowInstanceId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }

        public async Task<BusinessFlowInstanceEntity> GetEntity(long businessFlowInstanceId)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowInstanceId=?BusinessFlowInstanceId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowInstanceId", businessFlowInstanceId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<BusinessFlowInstanceEntity>(sql, parameters);
        }

        public async Task<IEnumerable<BusinessFlowInstanceEntity>> GetList(int companyId)
        {
            string sql = string.Format("{0} WHERE CompanyId=?CompanyId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CompanyId", companyId, DbType.Int32, size: 11);
            return await this.databaseContext.Slave.QueryAsync<BusinessFlowInstanceEntity>(sql, parameters);
        }

        public async Task<(IEnumerable<BusinessFlowInstanceEntity>, int)> Query(long? businessFlowModelId,string businessFlowInstanceName, DateTime? start, DateTime? end, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (businessFlowModelId.HasValue)
            {
                wheres.Add("BusinessFlowModelId=?BusinessFlowModelId");
                parameters.Add("?BusinessFlowModelId", businessFlowModelId, DbType.Int64, size: 20);
            }
            if (!string.IsNullOrWhiteSpace(businessFlowInstanceName))
            {
                wheres.Add("BusinessFlowInstanceName LIKE IN CONCAT('%',CONCAT(?BusinessFlowInstanceName,'%'))");
                parameters.Add("?BusinessFlowInstanceName", businessFlowInstanceName?.Trim(), DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime DESC LIMIT {2},{3}; SELECT COUNT(1) FROM OA_BusinessFlowInstance {1}",
                   QUERY,
                   wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                   (pageIndex - 1) * pageSize,
                   pageSize);
            return await this.databaseContext.Slave.QueryPageableListAsync<BusinessFlowInstanceEntity>(sql, parameters);
        }
    }
}
